package com.taxis.service;

import java.util.List;
import org.hibernate.*;
import com.taxis.common.*;
import com.taxis.model.Administrador;

public class AdministradorDaoService {

	private List<Administrador> administradores;
	private Administrador administrador;

	public AdministradorDaoService(){ }

	public void insertAdministrador(Administrador a) throws Exception{
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			session.save(a);
			tx.commit();
		}catch(RuntimeException re){
			if(a != null){
				tx.rollback();
			}
			throw re;
		}finally{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Administrador> getAllAdministradores() {
		Session session = HibernateUtil.currentSession();
		try {
			Query q = session.getNamedQuery("getAllPeticiones");
			administradores = (List<Administrador>)q.list();
			return administradores;
		} catch(Exception e) {
			System.out.println("Error while fetching PETICIONES");
			e.printStackTrace();
			return null;
		} finally {
			session.close();        	
		}
	}

	public Administrador getAdministrador(Integer idAdministrador) throws Exception {
		Session session = HibernateUtil.currentSession();
		try {
			return (Administrador)session.get(Administrador.class, idAdministrador);
		} finally {
			session.close();
		}
	}

	public void updateAdministrador(Administrador a) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(a);
			tx.commit();
		} catch(RuntimeException re) {
			if(a != null)
				tx.rollback();
			throw re;
		} finally {
			session.close();
		}
	}

	public void deleteAdministrador(Integer idAdministrador) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			administrador = (Administrador)session.load(Administrador.class, idAdministrador);
			session.delete(administrador);
			tx.commit();
		} catch (RuntimeException e) {
			if(administrador != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	
	public Administrador findByUsernameAndPasswordA(String usuario, String password) {
		Session session = HibernateUtil.currentSession();
		try {
			Query q = session.getNamedQuery("findByUsernameAndPasswordA");
			q.setString("usuario", usuario); q.setString("password",password);
			return (Administrador)q.uniqueResult();
		} catch(Exception e) {
			System.out.println("Error while fetching USUARIO");
			e.printStackTrace();
			return null;
		} finally {
			session.close();        	
		}
	}
}